package com.drinks.yiniang.ui.activity.user.milepost;

import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.drinks.yiniang.R;
import com.drinks.yiniang.adapter.listview.WineAnalyseAdapter;
import com.drinks.yiniang.adapter.user.milepost.MilepostAdapter;
import com.drinks.yiniang.entity.common.RadarEntity;
import com.drinks.yiniang.entity.shop.ShopJson;
import com.drinks.yiniang.entity.user.milepost.MilepostUnlockJson;
import com.drinks.yiniang.entity.user.milepost.WineAnalyseJson;
import com.drinks.yiniang.entity.user.points.PointsExchangeJson;
import com.drinks.yiniang.io.api.MilepostApiIO;
import com.drinks.yiniang.ui.widget.recycler.BaseRecyclerView;
import com.drinks.yiniang.ui.widget.view.RadarMapView;
import com.drinks.yiniang.utils.GlideUtils;
import com.drinks.yiniang.utils.ToastUtils;
import com.hansen.library.Constants;
import com.hansen.library.io.tuple.Tuple2;
import com.hansen.library.listener.APIRequestCallback;
import com.hansen.library.listener.OnNavgationBarClickListener;
import com.hansen.library.ui.activity.BaseTranBarActivity;
import com.hansen.library.ui.widget.image.CircleImageView;
import com.hansen.library.ui.widget.listview.NoScrollListView;
import com.hansen.library.ui.widget.nav.NavigationBarLayout;
import com.hansen.library.utils.CommonUtils;
import com.hansen.library.utils.ScreenSizeUtils;
import com.hansen.library.utils.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 里程碑页面
 *
 * @author han
 * @date 2019/09/10
 */
public class MilepostActivity extends BaseTranBarActivity implements OnNavgationBarClickListener, AdapterView.OnItemClickListener,
        BaseQuickAdapter.RequestLoadMoreListener {

    //nav
    private NavigationBarLayout nav_bar_milepost;
    private BaseRecyclerView rcv_milepost;

    //header view
    //头像
    private CircleImageView iv_milepost_avatar;
    //昵称
    private TextView tv_milepost_nickname;
    //消费总瓶数
    private TextView tv_milepost_total_bottles;
    //雷达图
    private RadarMapView chart_radar_map;
    private NoScrollListView gv_milepost_wine_analyse;

    private MilepostAdapter mMilepostAdapter;
    //酒类分析adapter
    private WineAnalyseAdapter mWineAnalyseAdapter;

    private List<WineAnalyseJson.WineAnalyseList> mList;

    private int mPages;

    @Override
    protected void initView() {
        nav_bar_milepost = findViewById(R.id.nav_bar_milepost);

        rcv_milepost = findViewById(R.id.rcv_milepost);
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        mContext = this;

        initAdapter();
        initAnalyseAdapter();
        getMilepostData();
        getRecentUnlockList();
    }

    private void initAdapter() {
        rcv_milepost.setLayoutManager(new LinearLayoutManager(mContext));

        mMilepostAdapter = new MilepostAdapter(mContext, new ArrayList<MilepostUnlockJson.MilepostUnlockList>());
        mMilepostAdapter.addHeaderView(getHeaderView());
        mMilepostAdapter.setHeaderAndEmpty(true);
        mMilepostAdapter.setCommonEmpty(getLayoutInflater(), rcv_milepost);
        mMilepostAdapter.bindToRecyclerView(rcv_milepost);
    }

    private void initAnalyseAdapter() {
        mList = new ArrayList<>();

        mWineAnalyseAdapter = new WineAnalyseAdapter(mContext, mList);

        gv_milepost_wine_analyse.setOnItemClickListener(this);
        gv_milepost_wine_analyse.setAdapter(mWineAnalyseAdapter);
    }

    //获取header
    private View getHeaderView() {
        View mHeaderView = getLayoutInflater().inflate(R.layout.header_milepost, (ViewGroup) rcv_milepost.getParent(), false);

        iv_milepost_avatar = mHeaderView.findViewById(R.id.iv_milepost_avatar);

        tv_milepost_nickname = mHeaderView.findViewById(R.id.tv_milepost_nickname);
        tv_milepost_total_bottles = mHeaderView.findViewById(R.id.tv_milepost_total_bottles);

        chart_radar_map = mHeaderView.findViewById(R.id.chart_radar_map);

        gv_milepost_wine_analyse = mHeaderView.findViewById(R.id.gv_milepost_wine_analyse);

        setTotalBottles(null);

        return mHeaderView;
    }

    @Override
    protected void initListener() {
        nav_bar_milepost.setOnNavgationBarClickListener(this);
        mMilepostAdapter.setOnLoadMoreListener(this, rcv_milepost);
    }

    @Override
    public void widgetClick(View v) {

    }

    @Override
    public int getTranBarResID() {
        return R.layout.activity_milepost;
    }

    @Override
    public void onBackClick(View v) {
        finish();
    }

    @Override
    public void onEditClick(View v) {
        Intent intent = new Intent(mContext, MilepostShareActivity.class);
        startActivity(intent);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if(CommonUtils.isArrayIndexOutOfBounds(mList, position)) {
            return;
        }

        Intent intent = new Intent(mContext, MilepostDetailActivity.class);
        intent.putExtra(Constants.KeyCategoryId, mList.get(position).getId());
        startActivity(intent);
    }

    @Override
    public void onLoadMoreRequested() {
        MilepostApiIO.getInstance().getMilepostRecentUnlockList(mPages, new APIRequestCallback<MilepostUnlockJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(MilepostUnlockJson res) {
                if(mMilepostAdapter == null) {
                    return;
                }

                mPages++;
                mMilepostAdapter.addData(res.getData().getData());
                if(CommonUtils.isHasMoreData(res.getData().getData())) {
                    mMilepostAdapter.loadMoreComplete();
                } else {
                    mMilepostAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                mMilepostAdapter.loadMoreFail();
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取最近解锁列表
    private void getRecentUnlockList() {
        mPages = 1;

        MilepostApiIO.getInstance().getMilepostRecentUnlockList(mPages, new APIRequestCallback<MilepostUnlockJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(MilepostUnlockJson res) {
                if(mMilepostAdapter == null) {
                    return;
                }

                mPages++;
                mMilepostAdapter.getData().clear();
                mMilepostAdapter.addData(res.getData().getData());
                if(CommonUtils.isHasMoreData(res.getData().getData())) {
                    mMilepostAdapter.loadMoreComplete();
                } else {
                    mMilepostAdapter.loadMoreEnd();
                }
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                mMilepostAdapter.loadMoreFail();
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {

            }
        });
    }

    //获取里程碑数据
    private void getMilepostData() {
        showLoadingDialog();

        MilepostApiIO.getInstance().getMilepostData(new APIRequestCallback<WineAnalyseJson, Tuple2<Integer, String>>() {
            @Override
            public void onSuccess(WineAnalyseJson res) {
                setData(res.getData());
            }

            @Override
            public void onError(Tuple2<Integer, String> error) {
                ToastUtils.showShort(error._2);
            }

            @Override
            public void onComplete() {
                dismissDialog();
            }
        });
    }

    private void setData(WineAnalyseJson.WineAnalyseData data) {
        //头像
        GlideUtils.loadAvatar(mContext, iv_milepost_avatar, data.getAvatar());
        //昵称
        tv_milepost_nickname.setText(data.getUsername());
        //总瓶数
        setTotalBottles(data.getConsume_wine());

        int size = CommonUtils.getListSize(data.getStatistics());

        chart_radar_map.setVisibility(size >= 5 ? View.VISIBLE : View.GONE);

        if(data.getStatistics() != null) {
            mList.clear();
            mList.addAll(data.getStatistics());
            mWineAnalyseAdapter.notifyDataSetChanged();

            if(size >= 5) {
                List<RadarEntity> radarList = new ArrayList<>();

                for(WineAnalyseJson.WineAnalyseList radarData : data.getStatistics()) {
                    radarList.add(new RadarEntity(radarData.getName(), StringUtils.getInt(radarData.getTotal())));
                }

                chart_radar_map.setRadarData(radarList);
            }
        }
    }

    private void setTotalBottles(String total) {
        //总瓶数
        total = StringUtils.getNullEmptyConvertZero(total);
        SpannableStringBuilder builder = new SpannableStringBuilder(String.format(getString(R.string.text_total_bottles_format), total));

        int end = builder.length();
        int start = end - total.length();

        builder.setSpan(new StyleSpan(Typeface.BOLD), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        builder.setSpan(new AbsoluteSizeSpan(ScreenSizeUtils.sp2Px(mContext, 14)), start, end, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        tv_milepost_total_bottles.setText(builder);
    }
}
